/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.List;
import javax.swing.JOptionPane;
import model.Classe;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author JONATAS
 */
public class ClasseDAO {

    private Session session;
    // método construtor - igual ao nome da classe precedido por public

    public ClasseDAO() {
        session = HibernateUtil.getSessionFactory().openSession();
    }

    public void insert(Classe m) {
        Transaction t = session.beginTransaction();
        session.save(m);
        t.commit();
    }

    public void update(Classe m) {
        Transaction t = session.beginTransaction();
        session.merge(m);
        t.commit();
    }

    public void delete(Classe m) {
        Transaction t = session.beginTransaction();
        session.delete(m);
        t.commit();
    }

    public Classe findById(String id) {
        return (Classe) session.load(Classe.class, id);
    }

    public List<Classe> findAll() {
        return session.createCriteria(Classe.class).list(); // faz um select * from marca
    }

    public List<Classe> findByDescricao(String descricao) {

        Query q = session.createQuery("from Classe where upper(cla_descricao) like upper(:X)");         
        q.setParameter("X", "%" + descricao + "%");          
        return q.list();
    }

    public String getCode() {
        try{
        Query q = session.createSQLQuery("Select max(lpad(cast(cla_id as int)+1,2,0)) from Classe ");
        if (Integer.parseInt(q.uniqueResult().toString()) == 99) {
            JOptionPane.showMessageDialog(null, "Limite de cadastro excedido!");
            return "ERRO!";
        } else {
            System.out.println("Results -> " + q.uniqueResult().toString());
            return q.uniqueResult().toString();
        }}catch(java.lang.NullPointerException ex){
            return "01";
        }
    }
}




